﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Routine.Api.DtoParameters;
using RoutineApi.Entities;
using RoutineApi.Models;
using RoutineApi.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RoutineApi.Controllers
{
    [ApiController]
    [Route("api/companies")]
    public class CompaniesController : ControllerBase
    {
        private readonly ICompanyRepository _companyRepository;
        private readonly IMapper mapper;

        public CompaniesController(ICompanyRepository companyRepository, IMapper mapper)
        {
            if (companyRepository == null)
            {
                throw new ArgumentNullException(nameof(companyRepository));
            }
            if (mapper == null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }
            _companyRepository = companyRepository;
            this.mapper = mapper;
        }
        [HttpGet]
        [HttpHead]
        public async Task<ActionResult<IEnumerable<CompanyDto>>> GetCompanies([FromQuery]CompanyDtoParameters companyDtoParameters)
        {

            var companies = await _companyRepository.GetCompaniesAsync(companyDtoParameters);
            var companyModels = mapper.Map<IEnumerable<CompanyDto>>(companies);

            return Ok(companyModels);



        }
        [HttpGet("{companyId}",Name=nameof(GetCompanie))]

        public async Task<IActionResult> GetCompanie(Guid companyId)
        {

            var company = await _companyRepository.GetCompanyAsync(companyId);
            var companyModel = mapper.Map<CompanyDto>(company);
            if (company == null)
            {
                return NotFound();
            }
            return Ok(companyModel);


        }
        [HttpPost]
        public async Task<IActionResult> CreatCompanie([FromBody]CompanyAddDto company)
        {
            var entity = mapper.Map<Company>(company);
            _companyRepository.AddCompany(entity);
            await  _companyRepository.SaveAsync();
            var returnDto = mapper.Map<CompanyDto>(entity);
            return CreatedAtRoute(nameof(GetCompanie), new { companyId = entity.Id}, returnDto);
        }
    }
}
